package com.lingx.web.api.impl;

import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.lingx.utils.TokenUtils;
import com.lingx.web.api.IApi;
@Component
public class Api8008 extends AbstractAuthApi implements IApi{

	@Resource
	private JdbcTemplate jdbcTemplate;
	@Override
	public int getApiCode() {
		return 8008;
	}
	@Override
	public String getApiName() {
		return "获取未读消息或未推送消息";
	}
	@Override
	public Map<String, Object> api(Map<String, Object> params) {
		Map<String,Object> ret=IApi.getRetMap(1, "操作成功");
		String type=IApi.getParamString(params, "type", "push");
		String token=IApi.getParamString(params, "lingxtoken", "");
		String id=IApi.getParamString(params, "id", "");
		String userid=TokenUtils.getTokenDataUserId(token);
		List<Map<String,Object>> list=null;
		if("push".equals(type)) {//未推送消息
			list=this.jdbcTemplate.queryForList("select id,content,to_user_id,from_user_id,type,status,route_path from tlingx_message where to_user_id=? and is_push='0' order by id desc limit 10",userid);
		}else if("all".equals(type)){//未读消息
			list=this.jdbcTemplate.queryForList("select id,content,to_user_id,from_user_id,type,status,route_path from tlingx_message where to_user_id=? and status='1' order by id desc limit 10",userid);
		}else if("singleReaded".equals(type)){
			this.jdbcTemplate.update("update tlingx_message set status='2'  where id=?",id);
		}else if("allReaded".equals(type)) {
			this.jdbcTemplate.update("delete from tlingx_message where to_user_id=?",userid);
		}
		if(list!=null&&list.size()>0) {//设为已推送
			this.jdbcTemplate.update("update tlingx_message set is_push='1' where to_user_id=? and is_push='0'",userid);
		}
		if(list!=null) {
		/*	
		for(Map<String,Object> map:list) {
			if(map.get("content").toString().length()>20)
			map.put("content", map.get("content").toString().substring(0, 20)+"...");
		}*/
		ret.put("unread", this.jdbcTemplate.queryForObject("select count(*) from tlingx_message where to_user_id=? and status='1'", Integer.class,userid));
		
		}
		ret.put("data", list);
		return ret;
	}

	public boolean isLog() {
		return false;
	}
	
	@Scheduled(cron="0/30 0 1 * * ?")//自动删除一个月前的消息
	public void delete() {
		try {
			long ts=System.currentTimeMillis()-(36*1000*60*60*24l);
			String datetime=getDate(ts);
			this.jdbcTemplate.update("delete from tlingx_message where create_time<?",datetime);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//if(!dir.exists())dir.mkdirs();
	}
	
	public static String getDate(long ts) {
		String dateTime = MessageFormat.format("{0,date,yyyyMMddHHmmss}",
				new Object[] { new java.sql.Date(ts) });
		return dateTime;

	}
	
}
